package com.laolang.shop.modules.auth.service;

import com.laolang.shop.modules.auth.entity.TokenUser;
import com.laolang.shop.modules.sys.consts.entity.SysTenantConst;
import com.laolang.shop.modules.sys.entity.SysTenant;
import com.laolang.shop.modules.sys.entity.SysUser;
import com.laolang.shop.modules.sys.service.SysTenantService;
import com.laolang.shop.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * @author khlbat
 * @version 1.0
 * @date 2020/11/1 20:46
 */
@Component("UserDetailServiceImpl")
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysTenantService sysTenantService;


    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        TokenUser tokenUser = new TokenUser();

        SysUser sysUser = sysUserService.findByPhone(phone);
        if (null == sysUser) {
            return null;
        }
        SysTenant sysTenant = sysTenantService.getById(sysUser.getTenantId());
        if (!SysTenantConst.Status.NORMAL.getValue().equals(sysTenant.getStatus())) {
            return null;
        }
        tokenUser.setUserId(sysUser.getId());
        tokenUser.setTenantId(sysUser.getTenantId());
        tokenUser.setPhone(sysUser.getPhone());
        return tokenUser;
    }
}
